<?php
/**
* @author moufer<moufer@163.com>
* @copyright (c)2001-2009 Moufersoft
* @website www.modoer.com
*/
!defined('IN_MUDDER') && exit('Access Denied');

class MPWeiXinOAuth2 {

	private $authorize_url = 'https://open.weixin.qq.com/connect/oauth2/authorize';
	private $token_url = 'https://api.weixin.qq.com/sns/oauth2/access_token';
	private $appid = '';
	private $appsecret = '';
	
	function __construct($appid, $appsecret) {
		$this->appid = $appid;
		$this->appsecret = $appsecret;
	}

	public function getAuthorizeURL($callbackurl) {
		//appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
		$url = $this->authorize_url . '?'
			. 'appid=' . $this->appid
			. '&redirect_uri=' . urlencode($callbackurl)
			. '&response_type=code'
			. '&scope=snsapi_userinfo'
			. '&state='.G('session')->get_id()
			. '#wechat_redirect';
		return $url;
	}

	public function getAccessToken($code, $callbackurl) {
		//appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
		$token_url = $this->token_url . '?' 
			. 'appid='.$this->appid
			. '&secret='.$this->appsecret
			. '&code='.$code
			. '&grant_type=authorization_code';
		$info = http_get($token_url);
		$token = array();
		if($info) {
			$token = json_decode($info, true);
			if($token['errcode']) {
				@log_write('weixin_login', $info);
			}
		}
		return $token;
	}
}

class MPWeiXinClient {

	private $appid = '';
	private $appsecret = '';
	private $token = '';
	private $openid = '';
	
	function __construct($appid, $appsecret, $token, $openid='')
	{
		$this->appid = $appid;
		$this->appsecret = $appsecret;
		$this->token = $token;
		$this->openid = $openid;
	}

	function get_user_info()
	{
		$get_user_info = "https://api.weixin.qq.com/sns/userinfo?"
			. "access_token=" . $this->token
			. "&openid=" . $this->openid;
		$info = http_get($get_user_info);
		if(!$info) return;
		$arr = json_decode($info, true);
		if($arr['openid']) return $arr;
		if($arr['errcode']) {
			@log_write('weixin_login', $info);
		}
		return;
	}

}

/** end **/